<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

/**
 * @extends Service<SmsService>
 */
class SmsService extends Service
{

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient()
    {
        //AccessKey ID：：LTAI5tPyW5JS8qkaFtdgTMZh
        //AccessKey Secret：ybVoe3ljAmehngEVidGt4ieBae75Fc
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => 'LTAI5tPyW5JS8qkaFtdgTMZh',
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => 'ybVoe3ljAmehngEVidGt4ieBae75Fc'
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function sendSms($phoneNumbers, $code)
    {
        $TemplateParam = json_encode(['code' => $code]);
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "signName" => "多功能智慧功德灯",
            'templateCode' => "SMS_273825751",
            'templateParam' => $TemplateParam,
            "phoneNumbers" => $phoneNumbers,
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
        $res = json_decode(json_encode($res->body), true);
        if ($res['code'] !== 'OK' && $res['message'] !== 'OK') {
            throw new BusinessException('发送失败');
        }
        return true;
    }
}